<template>

  <a-modal v-model:visible="visible" title="盘点资产名单详情" :mask-closable="false" :esc-to-close="false"
    :width="width >= 1200 ? 1200 : '100%'" draggable>
    <fieldset>
      <legend>基础信息</legend>
      <a-descriptions :column="3" bordered>
        <a-descriptions-item label="项目">
          {{ getTypeText(dataDetail?.type) }}
        </a-descriptions-item>
        <a-descriptions-item label="任务名称">{{ dataDetail?.name }}</a-descriptions-item>
        <a-descriptions-item label="责任人">{{ dataDetail?.nickname }}</a-descriptions-item>
        <a-descriptions-item label="开始日期">{{ dataDetail?.startDate }}</a-descriptions-item>
        <a-descriptions-item label="结束日期">{{ dataDetail?.endDate }}</a-descriptions-item>
      </a-descriptions>
      <br />
    </fieldset>
    <fieldset>
      <legend>资产列表</legend>
      <GiTable title="" row-key="id" :data="dataList" :columns="columns" :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }" :pagination="pagination" :disabled-tools="['size']"
        :disabled-column-keys="['name']" @refresh="search">
        <template #toolbar-left>
          <a-input-search v-model="queryForm.fuzzy" placeholder="编号/名称/SN" allow-clear @search="search" />
          <a-button @click="reset">
            <template #icon><icon-refresh /></template>
            <template #default>重置</template>
          </a-button>
        </template>
        <template #toolbar-right>
          <a-button v-permission="['asset:check:task:items:export']" @click="onExport">
            <template #icon><icon-download /></template>
            <template #default>导出</template>
          </a-button>
        </template>
        <template #status="{ record }">
          <a-tag v-if="record.status == 0" color="green">待盘</a-tag>
          <a-tag v-if="record.status == 1" color="red">盘亏</a-tag>
          <a-tag v-if="record.status == 2" color="purple">已盘</a-tag>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-link v-if=" record.status == 0" v-permission="['asset:check:task:items:check']" title="处理盘点"
              @click="onCheck(record.id )">处理盘点</a-link>
          </a-space>
        </template>
      </GiTable>
      <br />

      <a-modal v-model:visible="visibleItem" @ok="save" @before-ok="handleBeforeOk" @cancel="">
        <template #title>
          处理盘点
        </template>
        <div>
          <GiForm ref="formRef" v-model="form" :columns="itemColumns" />
        </div>
      </a-modal>

    </fieldset>
  </a-modal>
</template>

<script setup lang="ts">
  import type { TableInstance } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { Message } from '@arco-design/web-vue'
  import { type CheckTaskDetailResp, type CheckItemDetailResp, getCheckTask, listCheckItem, updateCheckItem, exportCheckItem } from '@/apis/asset/check/task'
  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { useDownload, useTable } from '@/hooks'
  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'
  import { isMobile } from '@/utils'
  import has from '@/utils/has'

  const { width } = useWindowSize()

  const dataId = ref('')
  const dataDetail = ref < CheckItemDetailResp > ()
  const visible = ref(false)
  const itemId = ref('')
  const visibleItem = ref(false)

  const formRef = ref < InstanceType < typeof GiForm >> ()

  const getTypeText = (type: string) => {
    return typeMap[type] || '未知类型'
  }

  const typeMap = {
    0: '设备',
    1: '配件',
    2: '软件'
  }

  // 盘点
  const [form, resetForm] = useResetReactive({
    // todo 待补充
  })

  const statusMap: LabelValueItem[] = [
    { label: '盘到啦', value: 2 },
    { label: '没盘到', value: 1 }
  ]

  const itemColumns: ColumnItem[] = reactive([
    {
      label: '状态',
      field: 'status',
      type: 'radio-group',
      span: 24,
      required: true,
      props: {
        options: statusMap,
      },
    },
    {
      label: '描述',
      field: 'description',
      type: 'textarea',
      span: 24,
      props: {
        maxLength: 200,
      },
    },
  ])

  const queryForm = reactive < CheckItemQuery > ({
    fuzzy: undefined,
    taskId: undefined,
    sort: ['id,desc']
  })

  // 巡检项列表
  const {
    tableData: dataList,
    loading,
    pagination,
    search,
    handleDelete
  } = useTable((page) => listCheckItem({ ...queryForm, ...page }), { immediate: true })
  const columns: TableInstance['columns'] = [
    { title: '资产编号', dataIndex: 'code', slotName: 'code' },
    { title: '资产名称', dataIndex: 'name', slotName: 'name' },
    { title: '序列号', dataIndex: 'sn', slotName: 'sn' },
    { title: '状态', dataIndex: 'status', slotName: 'status' },
    { title: '盘点人', dataIndex: 'checkerName', slotName: 'checkerName' },
    { title: '描述', dataIndex: 'description', slotName: 'description' },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
      width: 160,
      align: 'center',
      fixed: !isMobile() ? 'right' : undefined,
      show: has.hasPermOr(['asset:check:task:items:check'])
    }
  ]

  // 重置
  const reset = () => {
    queryForm.fuzzy = undefined
    search()
  }

  // 查询详情
  const getDataDetail = async () => {
    const { data } = await getCheckTask(dataId.value)
    dataDetail.value = data
  }

  // 打开
  const onOpen = async (id: string) => {
    dataId.value = id
    await getDataDetail()
    visible.value = true
    queryForm.taskId = id
    search()
  }

  // 盘点
  const onCheck = async (id: string) => {
    visibleItem.value = true
    form.id = id
    itemId.value = id
  }

  const handleBeforeOk = async () => {
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
    } catch (error) {
      return false
    }
  };

  // 保存
  const save = async () => {
    try {
      await updateCheckItem(form, itemId.value)
      Message.success('盘点成功')
      resetForm()
      search()
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }

  // 导出
  const onExport = () => {
    useDownload(() => exportCheckItem(queryForm))
  }

  defineExpose({ onOpen })
</script>

<style scoped lang="scss">
  fieldset {
    padding: 15px 15px 0 15px;
    margin-bottom: 15px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }

  fieldset legend {
    color: rgb(var(--gray-10));
    padding: 2px 5px 2px 5px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }
</style>